package com.mes.biz.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.mes.biz.domain.*;
import com.mes.biz.domain.vo.*;
import com.mes.biz.mapper.BizCustomerMapper;
import com.mes.biz.mapper.BizCustomerPayableMapper;
import com.mes.biz.mapper.BizOrderMapper;
import com.mes.biz.service.*;
import com.mes.common.constant.BizConstants;
import com.mes.common.core.domain.BaseEntity;
import com.mes.common.core.domain.entity.SysDept;
import com.mes.common.core.domain.entity.SysUser;
import com.mes.common.core.domain.model.LoginUser;
import com.mes.common.core.page.PageDomain;
import com.mes.common.core.service.BaseServiceImpl;
import com.mes.common.exception.BizException;
import com.mes.common.utils.DateUtils;
import com.mes.common.utils.SecurityUtils;
import com.mes.common.utils.StringUtils;
import com.mes.common.utils.sql.SqlUtil;
import com.mes.framework.cache.DeptUtils;
import com.mes.framework.cache.UserUtils;
import com.mes.system.domain.SysNotice;
import com.mes.system.domain.SysTenant;
import com.mes.system.service.SysNoticeService;
import com.mes.system.service.SysTenantService;
import com.mes.system.strategy.AutoCodeUtil;
import org.apache.commons.compress.utils.Sets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 销售单Service业务层处理
 * @author hwg
 * @email hwg
 * @date 2023-05-15
 */
@Service
@Transactional(readOnly = true)
public class BizOrderServiceImpl extends BaseServiceImpl<BizOrderMapper, BizOrder> implements BizOrderService {

    private static final Logger log = LoggerFactory.getLogger(BizOrderServiceImpl.class);

    @Resource
    private BizOrderMapper bizOrderMapper;

    @Autowired
    private BizOrderProductService bizOrderProductService;

    @Autowired
    private BizOrderAttachService bizOrderAttachService;
    @Resource
    private AutoCodeUtil autoCodeUtil;

    @Resource
    private BizCustomerMapper bizCustomerMapper;
    @Resource
    private BizCustomerPayableService bizCustomerPayableService;

    @Resource
    private BizCustomerPayableMapper bizCustomerPayableMapper;
    @Resource
    private BizOrderProcessRecordService bizOrderProcessRecordService;

    @Resource
    private BizProductionOrderService bizProductionOrderService;

    @Resource
    private BizOrderInstallerService bizOrderInstallerService;

    @Resource
    private BizCustomerPayableDetailService bizCustomerPayableDetailService;
    @Resource
    private BizOrderMaterialService bizOrderMaterialService;

    @Resource
    private BizProductInventoryService bizProductInventoryService;
    @Resource
    private BizProductProcessPlanService bizProductProcessPlanService;
    @Resource
    private SysTenantService sysTenantService;
    @Resource
    private BizProductService bizProductService;
    @Resource
    private BizProductInventoryBookService bizProductInventoryBookService;
    @Resource
    private BizMeasureService bizMeasureService;
    @Resource
    private SysNoticeService sysNoticeService;
    @Resource
    private BizCustomerAccountService bizCustomerAccountService;


    /**
     * 查询销售单列表
     * @param bizOrder 销售单
     * @return 销售单
     */
    @Override
    public List<BizOrder> findList(BizOrder bizOrder) {
        if (StringUtils.isNotEmpty(bizOrder.getOrderStatus())){
            String[] status = bizOrder.getOrderStatus().split(",");
            bizOrder.setStatus(status);
        }
		List<BizOrder> bizOrderList = super.findList(bizOrder);
		if (!CollectionUtils.isEmpty(bizOrderList)) {
			bizOrderList.stream().forEach(dto -> {
                SysUser createUser = UserUtils.getSysUser(dto.getCreateBy());
                if (StringUtils.isNotEmpty(createUser.getDeptId())){
                    SysDept sysDept = DeptUtils.getSysDept(createUser.getDeptId());
                    if (null != sysDept){
                        dto.setDeptIdName(sysDept.getDeptName());
                    }
                }
				if (StringUtils.isNotEmpty(dto.getBiller())){
					SysUser sysUser = UserUtils.getSysUser(dto.getBiller());
					if (null != sysUser){
						dto.setBillerName(sysUser.getName());
					}
				}
			});
		}
        return bizOrderList;
    }

    /**
     * 分页查询销售单列表
     * @param bizOrder 销售单
     * @return 销售单
     */
    @Override
    public PageInfo<BizOrder> findPage(BizOrder bizOrder) {
		PageInfo<BizOrder> page = super.findPage(bizOrder);
		if (!CollectionUtils.isEmpty(page.getList())) {
            page.getList().stream().forEach(dto -> {
                SysUser createUser = UserUtils.getSysUser(dto.getCreateBy());
                if (StringUtils.isNotEmpty(createUser.getDeptId())){
					SysDept sysDept = DeptUtils.getSysDept(createUser.getDeptId());
					if (null != sysDept){
						dto.setDeptIdName(sysDept.getDeptName());
					}
				}
				if (StringUtils.isNotEmpty(dto.getBiller())){
					SysUser sysUser = UserUtils.getSysUser(dto.getBiller());
					if (null != sysUser){
						dto.setBillerName(sysUser.getName());
					}
				}
                if (StringUtils.isNotEmpty(dto.getCreateBy())){
                    SysUser sysUser = UserUtils.getSysUser(dto.getCreateBy());
                    if (null != sysUser){
                        dto.setCreateByName(sysUser.getName());
                    }
                }
                if (StringUtils.isNotEmpty(dto.getCustomernan())){
                    SysUser sysUser = UserUtils.getSysUser(dto.getCustomernan());
                    if (null != sysUser){
                        dto.setCustomernanName(sysUser.getName());
                    }
                }
            });
        }
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createOrder(BizOrder bizOrder) {
        String tenantId = SecurityUtils.getTenantId();
        bizOrder.setTenantId(tenantId);
        if(StringUtils.isEmpty(bizOrder.getOrderNumber())) {
            SysTenant sysTenant = sysTenantService.get(tenantId);
            if (StringUtils.isEmpty(sysTenant.getLeader())){
                throw new BizException("请联系管理员添加销售单前缀!");
            }
            String code = autoCodeUtil.genSerialCode("SALE_ORDER_CODE",sysTenant.getLeader());
            bizOrder.setOrderNumber(code);
        } else {
            if(getBizOrderByOrderNumber(bizOrder.getOrderNumber())!=null) {
                throw new BizException("订单编号已存在!");
            }
        }
        if(bizOrder.getProductList().size() > 0) {
            BigDecimal amount = bizOrder.getProductList().stream().map(BizOrderProduct::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            bizOrder.setSaleAmount(amount);
        }else {
            bizOrder.setSaleAmount(BigDecimal.ZERO);
        }
        bizOrder.setCollectedAmount(BigDecimal.ZERO);
        bizOrder.setOrderStatus(BaseEntity.AUDIT_STATUS);
        boolean res = save(bizOrder);
        if(res) {
            //写入销售单附件
            for (int i = 0; i < bizOrder.getAttachList().size(); i++) {
                BizOrderAttach orderAttach = new BizOrderAttach();
                orderAttach.setTenantId(tenantId);
                orderAttach.setOrderId(bizOrder.getId());
                orderAttach.setAttachPath(bizOrder.getAttachList().get(i));
                orderAttach.setType(1);
                bizOrderAttachService.save(orderAttach);
            }
            //写入销售单产品
            List<BizOrderProduct> productList = bizOrder.getProductList();
            if (productList !=null && productList.size()>0){
                for (BizOrderProduct bizOrderProduct : productList){
                    bizOrderProduct.setOrderId(bizOrder.getId());
                    bizOrderProduct.setTenantId(tenantId);
                    bizOrderProductService.save(bizOrderProduct);
                }
            }
            //写入销售单物料
            List<BizOrderMaterial> materialList = bizOrder.getMaterialList();
            if (materialList !=null && materialList.size()>0){
                for (BizOrderMaterial bizOrderMaterial : materialList){
//                    changeInventory(bizOrderMaterial);
                    bizOrderMaterial.setOrderId(bizOrder.getId());
                    bizOrderMaterial.setTenantId(tenantId);
                    bizOrderMaterialService.save(bizOrderMaterial);
                }
            }
            if (StringUtils.isNotEmpty(bizOrder.getMeasureId())){
                BizMeasure bizMeasure = bizMeasureService.get(bizOrder.getMeasureId());
                bizMeasure.setStatus("1");
                bizMeasure.setOrderId(bizOrder.getId());
                bizMeasureService.update(bizMeasure);
            }
        }
        return res;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOrder(BizOrder bizOrder) {
        if(StringUtils.isEmpty(bizOrder.getOrderNumber())) {
            throw new BizException("订单编号不能为空!");
        }
        BizOrder existsOrder= getBizOrderByOrderNumber(bizOrder.getOrderNumber());
        if(existsOrder!=null && !existsOrder.getId().equals(bizOrder.getId()) ) {
            throw new BizException("订单编号已存在!");
        }
        BigDecimal saleAmount = bizOrder.getSaleAmount();
        //修改单据后的销售金额差值
        BigDecimal oldSaleAmount =  BigDecimal.ZERO;
        BigDecimal purchaseAmount = BigDecimal.ZERO;

        List<BizOrderProduct> productList = bizOrder.getProductList();
        if (productList !=null && productList.size()>0){
            purchaseAmount = productList.stream().map(BizOrderProduct::getAmount).reduce(BigDecimal.ZERO,BigDecimal::add);
            if (saleAmount != null){
                oldSaleAmount=oldSaleAmount.add(purchaseAmount.subtract(saleAmount));
                if (!"1".equals(bizOrder.getOrderStatus())){
                    BizCustomerPayable bizCustomerPayable = bizCustomerPayableService.getBizCustomerPayableByCustomerId(bizOrder.getCustomerId());
                    if (null != bizCustomerPayable) {
                        bizCustomerPayable.setTotalAmount(bizCustomerPayable.getTotalAmount().add(oldSaleAmount));
                        bizCustomerPayable.setHasAmount(bizCustomerPayable.getHasAmount().add(oldSaleAmount));
                        bizCustomerPayableMapper.update(bizCustomerPayable);
                    }
                }
            }
        }
        bizOrder.setSaleAmount(purchaseAmount);
        boolean update = super.save(bizOrder);
        if(update) {
            if(bizOrder.getAttachList().size() > 0) {
                List<BizOrderAttach> attaches = bizOrderAttachService.getBizOrderAttachByOrderId(bizOrder.getId());
                for (int i = 0; i < attaches.size(); i++) {
                    BizOrderAttach orderAttach = attaches.get(i);
                    bizOrderAttachService.remove(orderAttach);
                }
                //写入销售单附件
                for (int i = 0; i < bizOrder.getAttachList().size(); i++) {
                    BizOrderAttach orderAttach = new BizOrderAttach();
                    orderAttach.setTenantId(bizOrder.getTenantId());
                    orderAttach.setOrderId(bizOrder.getId());
                    orderAttach.setAttachPath(bizOrder.getAttachList().get(i));
                    orderAttach.setType(1);
                    bizOrderAttachService.save(orderAttach);
                }
            }
            //写入销售单产品
            List<BizOrderProduct> bizOrderProductList = bizOrderProductService.getBizOrderProductByOrderId(bizOrder.getId());
            Set<String> productExistsSets = Sets.newHashSet();
            if (bizOrderProductList !=null && bizOrderProductList.size()>0){
                bizOrderProductList.forEach(existsVO -> {
                    productExistsSets.add(existsVO.getId());
                });
            }
            if (productList !=null && productList.size()>0){
                for (BizOrderProduct bizOrderProduct : productList){
                    bizOrderProduct.setOrderId(bizOrder.getId());
                    bizOrderProduct.setTenantId(bizOrder.getTenantId());
                    productExistsSets.remove(bizOrderProduct.getId());
                    bizOrderProductService.save(bizOrderProduct);
                    if (!"1".equals(bizOrder.getOrderStatus())){
                        BizCustomerPayableDetail detail = bizCustomerPayableDetailService.getInfoByOrderProductId(bizOrderProduct.getId(), bizOrder.getOrderNumber());
                        if (detail == null){
                            detail=new BizCustomerPayableDetail();
                            detail.setOrderProductId(bizOrderProduct.getId());
                            detail.setCustomerId(bizOrder.getCustomerId());
                            detail.setOrderNumber(bizOrder.getOrderNumber());
                            detail.setType("0");
                            detail.setTenantId(bizOrder.getTenantId());
                            detail.setTotalAmount(bizOrderProduct.getAmount());
                            detail.setPayAmount(BigDecimal.ZERO);
                            bizCustomerPayableDetailService.save(detail);
                        }else {
                            detail.setTotalAmount(bizOrderProduct.getAmount());
                            detail.setPayAmount(BigDecimal.ZERO);
                            bizCustomerPayableDetailService.save(detail);

                            List<BizCustomerPayableDetail> bizCustomerPayableDetailList = bizCustomerPayableDetailService.getBizCustomerPayableDetailByAccountCode(detail.getAccountCode(), null);
                            BigDecimal totalAmount = bizCustomerPayableDetailList.stream().map(BizCustomerPayableDetail::getTotalAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                            if(StringUtil.isNotEmpty(detail.getAccountCode())){
                                BizCustomerAccount bizCustomerAccount = bizCustomerAccountService.getBizCustomerAccountInfo(detail.getAccountCode());
                                bizCustomerAccount.setTotalAmount(totalAmount);
                                bizCustomerAccountService.save(bizCustomerAccount);
                            }
                        }
                    }
                }
            }
            if (productExistsSets.size()>0){
                String[] ids = productExistsSets.toArray(new String[0]);
                bizOrderProductService.deleteBizOrderProductByIds(ids);
            }

            //写入销售单物料
            Set<String> existsSets = Sets.newHashSet();
            List<BizOrderMaterial> bizOrderMaterialList = bizOrderMaterialService.getBizOrderMaterialByOrderId(bizOrder.getId());
            if (bizOrderMaterialList !=null && bizOrderMaterialList.size()>0){
                bizOrderMaterialList.forEach(existsVO -> {
                    existsSets.add(existsVO.getId());
                });
            }
            List<BizOrderMaterial> materialList = bizOrder.getMaterialList();
            if (materialList != null && materialList.size() > 0) {
                for (BizOrderMaterial bizOrderMaterial : materialList) {
                    bizOrderMaterial.setOrderId(bizOrder.getId());
                    bizOrderMaterial.setTenantId(bizOrder.getTenantId());
                    existsSets.remove(bizOrderMaterial.getId());
                    bizOrderMaterialService.save(bizOrderMaterial);
                }
            }
            if (existsSets.size()>0){
                String[] ids = existsSets.toArray(new String[0]);
                bizOrderMaterialService.deleteBizOrderMaterialByIds(ids);
            }
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOrderHead(BizOrder bizOrder) {
        return super.save(bizOrder);
    }
//    public boolean changeInventory(BizOrderMaterial bizOrderMaterial){
//        BizProductInventory bizProductInventory = bizProductInventoryService.getByProductIdAndSpaceId(bizOrderMaterial.getProductId(),bizOrderMaterial.getSpaceId());
//        if (bizProductInventory != null){
//            BigDecimal number = bizProductInventory.getNumber() == null ? BigDecimal.ZERO : bizProductInventory.getNumber();
//            BigDecimal number1 = bizOrderMaterial.getGainNumber();
//            if (number != null && number.compareTo(number1)>=0){
//                return true;
//            }else {
//                throw new BizException("库存不足！");
//            }
//        }
//        throw new BizException("库存不足！");
//    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean auditOrder(String orderId) {
        BizOrder bizOrder = super.get(orderId.split(":")[0]);
        String status = orderId.split(":")[1];
        if (StringUtils.isNotEmpty(status) && BaseEntity.STATUS_DISABLE.equals(status)){
            boolean b = bizCustomerPayableDetailService.checkAccountCodeByOrderNumber(bizOrder.getOrderNumber());
            if (b){
                throw new BizException("已生成对账,不能反审核");
            }
            if ("3".equals(bizOrder.getOrderType())){
                List<BizOrderMaterial> bizOrderMaterials = bizOrderMaterialService.getBizOrderMaterialByOrderId(bizOrder.getId());
                for (BizOrderMaterial bizOrderMaterial : bizOrderMaterials) {
                    BizProduct bizProduct = bizProductService.get(bizOrderMaterial.getProductId());
                    BizProductInventoryBook bizProductInventoryBook = bizProductInventoryBookService.
                            selectBizProductInventoryBookByOrderNumber(bizOrder.getOrderNumber(),bizOrderMaterial.getSpaceId(),bizProduct.getId());
                    BizProductInventory bizProductInventory = new BizProductInventory();
                    bizProductInventory.setWarehouseId(bizOrderMaterial.getWarehouseId());
                    bizProductInventory.setSpaceId(bizOrderMaterial.getSpaceId());
                    bizProductInventory.setProductId(bizProduct.getId());
                    BizProductInventory inventoryList = bizProductInventoryService.getByProductIdAndSpaceId(bizProduct.getId(),bizOrderMaterial.getSpaceId());
                    if(inventoryList!=null){
                        if (inventoryList.getNumber()!=null){
                            inventoryList.setNumber(inventoryList.getNumber().add(bizProductInventoryBook.getNumber()));
                        }else {
                            inventoryList.setNumber(bizProductInventoryBook.getNumber());
                        }
                        inventoryList.setAssistNumberA(inventoryList.getNumber().multiply(bizProduct.getConvertRatioA()).setScale(3,BigDecimal.ROUND_HALF_UP));
                        inventoryList.setAssistNumberB(inventoryList.getNumber().multiply(bizProduct.getConvertRatioB()).setScale(3,BigDecimal.ROUND_HALF_UP));
                        bizProductInventoryService.update(inventoryList);
                    }
                }
                //删除产品库存台账
                bizProductInventoryBookService.deleteBizProductInventoryBookByOrderNumber(bizOrder.getOrderNumber());
            }
        }
        if ("3".equals(bizOrder.getOrderType())){
            if (StringUtils.isNotEmpty(status) && BaseEntity.STATUS_DELETE.equals(status)){
                bizOrder.setOrderStatus(BaseEntity.INSTALL_STATUS);
                List<BizOrderMaterial> materialList = bizOrderMaterialService.getBizOrderMaterialByOrderId(bizOrder.getId());
                if (materialList != null && materialList.size() > 0) {
                    for (BizOrderMaterial orderMaterial : materialList) {
                        if (StringUtils.isEmpty(orderMaterial.getWarehouseId())) {
                            throw new BizException("产品编号:" + orderMaterial.getProductCode() + "的仓库不能为空");
                        }
                        if (StringUtils.isEmpty(orderMaterial.getSpaceId())) {
                            throw new BizException("产品编号:" + orderMaterial.getProductCode() + "的仓位不能为空");
                        }
                        updateInventory(orderMaterial, bizOrder);
                    }

                }
            }else {
                bizOrder.setOrderStatus(status);
            }
        }else {
            bizOrder.setOrderStatus(status);
        }
//        bizOrder.setOrderStatus(status);
        int update = bizOrderMapper.update(bizOrder);
        if(update > 0) {
            Random random = new Random();
            //把随机生成的数字转成字符串
            String str = String.valueOf(random.nextInt(9));
            for (int i = 0; i < 5; i++) {
                str += random.nextInt(9);
            }
            BizCustomerPayable bizCustomerPayable = bizCustomerPayableService.getBizCustomerPayableByCustomerId(bizOrder.getCustomerId());
            if(null == bizCustomerPayable) {
                bizCustomerPayable = new BizCustomerPayable();
                bizCustomerPayable.setPayableCode("YSZK" + str);
                bizCustomerPayable.setTotalAmount(bizOrder.getSaleAmount());
                bizCustomerPayable.setHasAmount(bizOrder.getSaleAmount());
                bizCustomerPayable.setPayAmount(BigDecimal.ZERO);
                bizCustomerPayable.setCustomerId(bizOrder.getCustomerId());
                bizCustomerPayable.setTenantId(bizOrder.getTenantId());
                BizCustomer bizCustomer = bizCustomerMapper.get(bizOrder.getCustomerId());
                bizCustomerPayable.setCustomerName(bizCustomer.getCustomerName());
                bizCustomerPayableService.save(bizCustomerPayable);
            }else {
                if ("1".equals(bizOrder.getOrderStatus())){
                    bizCustomerPayable.setTotalAmount(bizCustomerPayable.getTotalAmount().subtract(bizOrder.getSaleAmount()));
                    bizCustomerPayable.setHasAmount(bizCustomerPayable.getHasAmount().subtract(bizOrder.getSaleAmount()));
                }else {
                    bizCustomerPayable.setTotalAmount(bizCustomerPayable.getTotalAmount().add(bizOrder.getSaleAmount()));
                    bizCustomerPayable.setHasAmount(bizCustomerPayable.getHasAmount().add(bizOrder.getSaleAmount()));
                }
                bizCustomerPayableMapper.update(bizCustomerPayable);
            }
            List<BizOrderProduct> bizOrderProductList = bizOrderProductService.getBizOrderProductByOrderId(bizOrder.getId());
            if (bizOrderProductList != null && bizOrderProductList.size()>0){
                for (BizOrderProduct bizOrderProduct : bizOrderProductList){
                    if ("1".equals(bizOrder.getOrderStatus())){
                        bizCustomerPayableDetailService.deleteByOderProductId(bizOrderProduct.getId(),bizOrder.getOrderNumber());
                    }else {
                        BizCustomerPayableDetail payableDetail = new BizCustomerPayableDetail();
                        payableDetail.setOrderProductId(bizOrderProduct.getId());
                        payableDetail.setCustomerId(bizCustomerPayable.getCustomerId());
                        payableDetail.setTotalAmount(bizOrderProduct.getAmount());
                        payableDetail.setPayAmount(BigDecimal.ZERO);
                        payableDetail.setOrderNumber(bizOrder.getOrderNumber());
                        payableDetail.setTenantId(bizOrder.getTenantId());
                        payableDetail.setType("0");
                        bizCustomerPayableDetailService.save(payableDetail);
                    }
                }
            }
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean endOrder(String orderId) {
        BizOrder bizOrder = super.get(orderId);
        bizOrder.setOrderStatus(BaseEntity.END_STATUS);
        int update = bizOrderMapper.update(bizOrder);
        if(update > 0) {
            //查询销售单明细
            return true;
        }
        return false;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean changeOrder(String orderId) {
        BizOrder bizOrder = super.get(orderId.split(":")[0]);
        String s = orderId.split(":")[1];
        if (StringUtils.isNotEmpty(s) && "6".equals(s)){
            List<BizOrderProcessRecord> list = bizOrderProcessRecordService.getByOrderId(bizOrder.getId());
            if (list != null && list.size()>0){
                for (BizOrderProcessRecord bizOrderProcessRecord : list) {
                    if ("0".equals(bizOrderProcessRecord.getCompletedVol())){
                        bizOrderProcessRecord.setCompletedVol("1");
                        bizOrderProcessRecord.setCreator(SecurityUtils.getUserId());
                        bizOrderProcessRecordService.save(bizOrderProcessRecord);
                    }
                }

            }
        }
        bizOrder.setOrderStatus(s);
        int update = bizOrderMapper.update(bizOrder);
        if(update > 0) {
            //查询销售单明细
            return true;
        }
        return false;
    }

//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public boolean processOrder(BizOrder bizOrder) {
//        BizOrder temp = get(bizOrder.getId());
//        temp.setOrderStatus("3");
//        int update = bizOrderMapper.update(temp);
//        if(update > 0){
//            List<BizOrderProduct> productList = bizOrderProductService.getBizOrderProductByOrderId(bizOrder.getId());
//            if (productList != null && productList.size()>0){
//                for (BizOrderProduct bizOrderProduct: productList){
//                    List<BizProductionProcess> list = bizProductProcessPlanService.getCompletionByProductId(bizOrderProduct.getProductId());
//                    for (BizProductionProcess bizProductionProcess : list){
//                        BizOrderProcessRecord processRecord = new BizOrderProcessRecord();
//                        processRecord.setOrderId(bizOrder.getId());
//                        processRecord.setProductId(bizOrderProduct.getProductId());
//                        processRecord.setCompletedVol("0");
//                        processRecord.setTenantId(temp.getTenantId());
//                        processRecord.setProcessId(bizProductionProcess.getId());
//                        processRecord.setProcessCode(bizProductionProcess.getProcessCode());
//                        processRecord.setProcessName(bizProductionProcess.getProcessName());
//                        processRecord.setUnitSalary(bizProductionProcess.getUnitSalary());
//                        processRecord.setProcessVol(bizOrderProduct.getNumber());
//                        processRecord.setProcessPlanId(bizOrderProduct.getPlanId());
//                        processRecord.setUnit(bizOrderProduct.getUnit());
//                        processRecord.setSortNumber(bizProductionProcess.getSortNumber());
//                        processRecord.setOrderProductId(bizOrderProduct.getId());
//                        bizOrderProcessRecordService.save(processRecord);
//                    }
//                }
//            }
//            return true;
//        }
//        return false;
//    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean processOrder(BizOrder bizOrder) {
        BizOrder temp = get(bizOrder.getId());
        if ("2".equals(temp.getOrderStatus())) {
            temp.setOrderStatus("3");
        }
        temp.setOrderDate(new Date());
        int update = bizOrderMapper.update(temp);
        if(update > 0){
            bizOrderProcessRecordService.deleteByOrderId(temp.getId());
            List<BizOrderProcessRecord> recordList = bizOrder.getRecordList();
            if (recordList != null && recordList.size()>0){
                for (BizOrderProcessRecord processRecord : recordList){
                    if (StringUtils.isEmpty(processRecord.getProcessId())){
                        throw new BizException("工序id不能为空");
                    }
                    if (StringUtils.isEmpty(processRecord.getProcessPlanId())){
                        throw new BizException("工序计划id不能为空");
                    }
                    processRecord.setOrderId(temp.getId());
                    if (StringUtils.isEmpty(processRecord.getCompletedVol())){
                        processRecord.setCompletedVol("0");
                    }
                    processRecord.setTenantId(temp.getTenantId());
                    processRecord.setId(null);
                    bizOrderProcessRecordService.save(processRecord);
                }
            }
        }
        return true;
    }

    @Transactional
    @Override
    public boolean spplementOrder(BizOrder bizOrder) {
        BizOrder newOrder = new BizOrder();
        BeanUtils.copyProperties(bizOrder,newOrder);
        newOrder.setId(IdWorker.getIdStr());
        int count = bizOrderMapper.countOrder(bizOrder.getOrderNumber());
        String code = bizOrder.getOrderNumber() + "-B-00" + (count + 1);
        newOrder.setOrderNumber(code);
        newOrder.setOriginalOrder(bizOrder.getOrderNumber());
        if(bizOrder.getProductList().size() > 0) {
            BigDecimal amount = bizOrder.getProductList().stream().map(BizOrderProduct::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            newOrder.setSaleAmount(amount);
        }else {
            newOrder.setSaleAmount(BigDecimal.ZERO);
        }
        newOrder.setCollectedAmount(BigDecimal.ZERO);
        newOrder.setOrderStatus(bizOrder.getOrderStatus());
        int insert = bizOrderMapper.insert(newOrder);
        if(insert > 0) {
            //写入销售单附件
            for (int i = 0; i < bizOrder.getAttachList().size(); i++) {
                BizOrderAttach orderAttach = new BizOrderAttach();
                orderAttach.setTenantId(newOrder.getTenantId());
                orderAttach.setOrderId(newOrder.getId());
                orderAttach.setAttachPath(bizOrder.getAttachList().get(i));
                orderAttach.setType(1);
                bizOrderAttachService.save(orderAttach);
            }
            //写入销售单产品
            for (int i = 0; i < bizOrder.getProductList().size(); i++) {
                BizOrderProduct bizOrderProduct = new BizOrderProduct();
                bizOrderProduct.setOrderId(newOrder.getId());
                bizOrderProduct.setTenantId(newOrder.getTenantId());
                bizOrderProduct.setProductId(bizOrder.getProductList().get(i).getId());
                bizOrderProduct.setAmount(bizOrder.getProductList().get(i).getAmount());
                bizOrderProduct.setNumber(bizOrder.getProductList().get(i).getNumber());
                bizOrderProduct.setPrice(bizOrder.getProductList().get(i).getPrice());
                bizOrderProduct.setUnit(bizOrder.getProductList().get(i).getUnit());
                bizOrderProductService.save(bizOrderProduct);
            }
            //写入销售单物料
            return true;
        }
//        if(insert > 0) {
//            //写入销售单附件
//            for (int i = 0; i < bizOrder.getAttachList().size(); i++) {
//                BizOrderAttach orderAttach = new BizOrderAttach();
//                orderAttach.setTenantId(newOrder.getTenantId());
//                orderAttach.setOrderId(bizOrder.getId());
//                orderAttach.setAttachPath(bizOrder.getAttachList().get(i));
//                orderAttach.setType(1);
//                bizOrderAttachService.save(orderAttach);
//            }
//            //写入销售单产品
//            List<BizOrderProduct> productList = bizOrder.getProductList();
//            if (productList !=null && productList.size()>0){
//                for (BizOrderProduct bizOrderProduct : productList){
//                    bizOrderProduct.setOrderId(bizOrder.getId());
//                    bizOrderProduct.setTenantId(newOrder.getTenantId());
//                    bizOrderProductService.save(bizOrderProduct);
//                }
//            }
//            //写入销售单物料
//            List<BizOrderMaterial> materialList = bizOrder.getMaterialList();
//            if (materialList !=null && materialList.size()>0){
//                for (BizOrderMaterial bizOrderMaterial : materialList){
////                    changeInventory(bizOrderMaterial);
//                    bizOrderMaterial.setOrderId(bizOrder.getId());
//                    bizOrderMaterial.setTenantId(newOrder.getTenantId());
//                    bizOrderMaterialService.save(bizOrderMaterial);
//                }
//            }
//
//        }
        return false;
    }

    @Override
    @Transactional
    public boolean installOrder(BizOrder bizOrder) {
        BizOrder temp = get(bizOrder.getId());
        temp.setOrderStatus(BaseEntity.INSTALL_STATUS);
        int update = bizOrderMapper.update(temp);
        if(update > 0){
            for (int i = 0; i < bizOrder.getUserList().size(); i++) {
                BizOrderInstaller orderInstaller = new BizOrderInstaller();
                orderInstaller.setOrderId(bizOrder.getId());
                orderInstaller.setUserId(bizOrder.getUserList().get(i));
                orderInstaller.setTenantId(temp.getTenantId());
                bizOrderInstallerService.save(orderInstaller);
            }
            return true;
        }
        return false;
    }

    @Override
    @Transactional
    public boolean sinkArrivalOrder(BizOrder bizOrder) {
        if("0".equals(bizOrder.getFlag())){
            bizOrder.setSinkArrival("");
        }else {
            bizOrder.setSinkArrival(BaseEntity.SINK_STATUS);
        }
        int update = bizOrderMapper.update(bizOrder);
        if(update > 0) {
            return true;
        }
        return false;
    }

    @Override
    public List<BizOrder> getBizOrderByProjectId(String projectId) {
        return bizOrderMapper.getBizOrderByProjectId(projectId);
    }

    @Override
    public BizOrder getBizOrderByOrderNumber(String orderNumber) {
        return bizOrderMapper.getBizOrderByOrderNumber(orderNumber);
    }

    @Override
    public PageInfo<BizOrder> appletProcessList(BizOrder bizOrder, String userId) {
        PageDomain page = bizOrder.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        return new PageInfo(bizOrderMapper.appletProcessList(bizOrder.getOrderParams(),bizOrder.getOrderNumber(),bizOrder.getProcessStatus(), userId));
    }

    @Override
    public PageInfo<BizOrder> AftermarketAppletList(BizOrder bizOrder) {
        PageDomain page = bizOrder.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        return new PageInfo(bizOrderMapper.AftermarketAppletList(bizOrder));
    }

    @Override
    public PageInfo<BizOrder> pickingList(BizOrder bizOrder) {
        PageDomain page = bizOrder.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        return new PageInfo(bizOrderMapper.pickingList(bizOrder));
    }

//    @Transactional
//    @Override
//    public boolean staffAllocation(OrderInstall orderInstall) {
//        if (StringUtils.isNotEmpty(orderInstall.getInstallerType())){
//            BizOrder bizOrder = super.get(orderInstall.getOrderId());
//            if ("1".equals(orderInstall.getInstallerType())){
//                if ("1".equals(bizOrder.getDeliveryType())){
//                    throw new BizException("当前单据配送模式为客户自提，不能设置配送人员，请联系管理员！");
//                }
//                boolean flag = bizOrderInstallerService.getInstallerByOrderId(orderInstall.getOrderId(), orderInstall.getInstallerType());
//                if (flag){
//                    throw new BizException("当前单据安装模式为无安装，不能设置安装人员，请联系管理员！");
//                }
//            }else if("2".equals(orderInstall.getInstallerType())){
//                if ("1".equals(bizOrder.getInstallType())){
//                    throw new BizException("当前单据安装模式为无安装，不能设置安装人员，请联系管理员！");
//                }
//            }
//        }else {
//            throw new BizException("类型不能为空");
//        }
//        return false;
//    }

    @Override
    public PageInfo<BizOrder> vehicleDispatchList(BizOrder bizOrder, String userId) {
        PageDomain page = bizOrder.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        return new PageInfo(bizOrderMapper.vehicleDispatchList(bizOrder.getOrderParams(),bizOrder.getOrderNumber(),
                bizOrder.getInstallerStatus(),bizOrder.getInstallerType(),bizOrder.getStatus(),userId,bizOrder.getShippingStatus()));
    }

    @Transactional
    @Override
    public boolean saveWarehouse(BizOrder bizOrder) {
        BizOrder bizOrder1 = super.get(bizOrder.getId());
//        BizOrder bizOrder1 = new BizOrder();
        bizOrder1.setProductWarehouseId(bizOrder.getProductWarehouseId());
        bizOrder1.setProductWarehouse(bizOrder.getProductWarehouse());
        return bizOrderMapper.update(bizOrder1)>0;
    }

    @Transactional
    @Override
    public boolean shipments(BizOrder bizOrder) {
        BizOrder bizOrder1 = super.get(bizOrder.getId());
        if (BaseEntity.IS_HAHDLE.equals(bizOrder1.getShippingStatus())){
            throw new BizException("已发货状态，不能继续发货");
        }
        if (BaseEntity.IS_HAHDLE.equals(bizOrder1.getInstallType())){
            //无安装时，更新状态同时完成订单
            bizOrder1.setOrderStatus(BaseEntity.STATUS_DRAFT);
        }
        bizOrder1.setShippingStatus(bizOrder.getShippingStatus());
        return bizOrderMapper.update(bizOrder1)>0;
    }

    @Transactional
    public void updateInventory(BizOrderMaterial bizOrderMaterial, BizOrder bizOrder1){
        BigDecimal gainNumber = bizOrderMaterial.getNumber();
        String remark=null;
        if (gainNumber == null){
            throw new BizException("数量不能为空！");
        }
//        if (StringUtils.isEmpty(bizOrderMaterial.getUnit())){
//            throw new BizException("单位不能为空！");
//        }
        if ("2".equals(bizOrderMaterial.getProductType())){
            gainNumber=BigDecimal.ZERO.subtract(gainNumber);
        }else if ("1".equals(bizOrderMaterial.getProductType())) {
            remark = "补料";
        }
        bizOrderMaterial.setReceivedNumber((gainNumber));
        bizOrderMaterial.setNumber((gainNumber));
        String tenantId = SecurityUtils.getTenantId();
        bizOrderMaterial.setTenantId(tenantId);
        bizOrderMaterialService.save(bizOrderMaterial);
        BizProductInventory bizProductInventory = bizProductInventoryService.getByProductIdAndSpaceId(bizOrderMaterial.getProductId(),
                bizOrderMaterial.getSpaceId());
        BizProduct bizProduct = bizProductService.get(bizOrderMaterial.getProductId());
        if (bizProduct.getInventoryFlag() != null && "1".equals(bizProduct.getInventoryFlag())) {
            //计算基础数量
            BigDecimal basicNumber = ConvertRatioNumberUnit.convertRatio(gainNumber, bizOrderMaterial.getUnit(), bizProduct);
            if (bizProductInventory != null) {
                BigDecimal number = bizProductInventory.getNumber() == null ? BigDecimal.ZERO : bizProductInventory.getNumber();
                if (number != null && number.compareTo(basicNumber) >= 0) {
                    bizProductInventory.setNumber(number.subtract(basicNumber));
                    bizProductInventory.setAssistNumberA(bizProductInventory.getNumber().multiply(bizProduct.getConvertRatioA()).setScale(3, BigDecimal.ROUND_HALF_UP));
                    bizProductInventory.setAssistNumberB(bizProductInventory.getNumber().multiply(bizProduct.getConvertRatioB()).setScale(3, BigDecimal.ROUND_HALF_UP));
                    bizProductInventoryService.save(bizProductInventory);
                } else {
                    throw new BizException("库存不足！");
                }
            } else {
                if ("2".equals(bizOrderMaterial.getProductType())) {
                    bizProductInventory = new BizProductInventory();
                    bizProductInventory.setProductId(bizOrderMaterial.getProductId());
                    bizProductInventory.setSpaceId(bizOrderMaterial.getSpaceId());
                    bizProductInventory.setWarehouseId(bizOrderMaterial.getWarehouseId());
                    bizProductInventory.setNumber(BigDecimal.ZERO.subtract(basicNumber));
                    bizProductInventory.setAssistNumberA(bizProductInventory.getNumber().multiply(bizProduct.getConvertRatioA()).setScale(3, BigDecimal.ROUND_HALF_UP));
                    bizProductInventory.setAssistNumberB(bizProductInventory.getNumber().multiply(bizProduct.getConvertRatioB()).setScale(3, BigDecimal.ROUND_HALF_UP));
                    bizProductInventory.setTenantId(SecurityUtils.getTenantId());
                    bizProductInventoryService.save(bizProductInventory);
                } else {
                    throw new BizException("未查询到当前库存数据");
                }
            }
            BizProductInventoryBook productInventoryBook = new BizProductInventoryBook();
            productInventoryBook.setBizDate(DateUtils.getNowDate());
            productInventoryBook.setUnit(bizProduct.getUnit());
            productInventoryBook.setAssistUnitA(bizProduct.getAssistUnitA());
            productInventoryBook.setAssistUnitB(bizProduct.getAssistUnitB());
            productInventoryBook.setInventoryId(bizProductInventory.getId());
            productInventoryBook.setNumber(basicNumber);
            productInventoryBook.setAssistNumberB(basicNumber.multiply(bizProduct.getConvertRatioB()).setScale(3, BigDecimal.ROUND_HALF_UP));
            productInventoryBook.setAssistNumberA(basicNumber.multiply(bizProduct.getConvertRatioA()).setScale(3, BigDecimal.ROUND_HALF_UP));
//            productInventoryBook.setOrderNumber(bizOrderMaterial.getPurchaseCode());
            productInventoryBook.setOrderType(BizConstants.ORDER_TYPE_PURCHASE);
            productInventoryBook.setProductModel(bizProduct.getModel());
            productInventoryBook.setTenantId(SecurityUtils.getTenantId());
            productInventoryBook.setProductId(bizProduct.getId());
            productInventoryBook.setCustomer(bizOrder1.getCustomerId());
            productInventoryBook.setRemark(bizOrderMaterial.getRemark());
            productInventoryBook.setOrderType("1");
            productInventoryBook.setOrderNumber(bizOrder1.getOrderNumber());
            productInventoryBook.setRemark(remark);
            productInventoryBook.setSpaceId(bizOrderMaterial.getSpaceId());
            productInventoryBook.setWarehouseId(bizOrderMaterial.getWarehouseId());
            bizProductInventoryBookService.save(productInventoryBook);
        }
    }

    @Override
    public boolean checkAddressUnique(BizOrder bizOrder) {
        boolean flag=false;
        BizOrder order=new BizOrder();
        order.setNotEqualId(bizOrder.getId());
        order.setAddress(bizOrder.getAddress());
        if (!CollectionUtils.isEmpty(mapper.findListWithUnique(order))) {
            flag=true;
        }
        return flag;
    }

    @Override
    public PageInfo<OrderVo> listOrderStatPage(BizOrder bizOrder) {
        PageDomain page = bizOrder.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        return new PageInfo(bizOrderMapper.listOrderStat(bizOrder));
    }

    @Override
    public List<OrderVo> listOrderStat(BizOrder bizOrder) {
       return bizOrderMapper.listOrderStat(bizOrder);
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean returnProcessOrder(BizOrder bizOrder) {
        BizOrder temp = get(bizOrder.getId());
        if ("3".equals(temp.getOrderStatus())) {
            temp.setOrderStatus("2");
        }else {
            throw new BizException("只有待领料状态才能取消生产");
        }
        temp.setOrderDate(new Date());
        int update = bizOrderMapper.update(temp);
        if(update > 0){
            bizOrderProcessRecordService.deleteByOrderId(temp.getId());
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean complete(BizOrder bizOrder) {
        BizOrder temp = get(bizOrder.getId());
        if ("7".equals(temp.getOrderStatus())) {
            temp.setOrderStatus("9");
            temp.setShippingStatus("1");
        }else {
            throw new BizException("已派单的单据才能完成订单");
        }
        int update = bizOrderMapper.update(temp);
        if(update > 0){
            List<BizOrderInstaller> installerList = bizOrderInstallerService.getBizOrderInstallerByOrderId(temp.getId(),null);
            if (installerList != null && installerList.size()>0){
                for (BizOrderInstaller bizOrderInstaller : installerList){
                    bizOrderInstaller.setInstallerStatus("2");
                    bizOrderInstallerService.save(bizOrderInstaller);
                }
            }
        }
        return true;
    }

    @Override
    public PageInfo<OrderTrackingVo> orderTrackingList(BizOrder bizOrder) {
        PageDomain page = bizOrder.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        return new PageInfo(bizOrderMapper.orderTrackingList(bizOrder));
    }

    @Override
    public PageInfo<PieceProductionVo> pieceProductionList(BizOrder bizOrder) {
        PageDomain page = bizOrder.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        return new PageInfo(bizOrderMapper.pieceProductionList(bizOrder));
    }

    @Override
    public List<PieceProductionVo> printPieceProductionList(BizOrder bizOrder) {

        return bizOrderMapper.pieceProductionList(bizOrder);
    }

    @Override
    public BizOrder findById(BizOrder bizOrder) {
        return bizOrderMapper.findById(bizOrder);
    }

    @Override
    public Map<String, Object> getSaleOrderDataByToday() {
        return bizOrderMapper.getSaleOrderDataByToday();
    }

    @Override
    public Map<String, Object> getProductDataByToday() {
        return bizOrderMapper.getProductDataByToday();
    }

    @Override
    public Map<String, Object> getCompleteDataByToday() {
        return bizOrderMapper.getCompleteDataByToday();
    }

    @Override
    public Map<String, Object> getDispatchDataByToday() {
        return bizOrderMapper.getDispatchDataByToday();
    }

    @Override
    public Map<String, Object> getInstallerDataByToday() {
        return bizOrderMapper.getInstallerDataByToday();
    }

    @Override
    public Map<String, Object> getMeasureDataByToday() {
        return bizOrderMapper.getMeasureDataByToday();
    }

    @Override
    public List<Map<String, Object>> getThisMonthOrderAmountData() {
        return bizOrderMapper.getThisMonthOrderAmountData();
    }

    @Override
    public List<Map<String, Object>> getLastMonthOrderAmountData() {
        return bizOrderMapper.getLastMonthOrderAmountData();
    }

    @Override
    public List<Map<String, Object>> getSaleOrderDataByMonth() {
        return bizOrderMapper.getSaleOrderDataByMonth();
    }

    @Override
    public BigDecimal getSaleOrderAmountByMonth(String dateStr) {
        return bizOrderMapper.getSaleOrderAmountByMonth(dateStr);
    }

//    @Transactional(rollbackFor = Exception.class)
//    @Override
//    public void ProcessWarning() {
//        List<BizOrderWithProduct> bizOrderList = bizOrderMapper.findListByProcess();
//        if (bizOrderList!=null && bizOrderList.size()>0){
//            for (BizOrderWithProduct order : bizOrderList) {
//                BizOrderProcessRecord bizOrderProcessRecord = new BizOrderProcessRecord();
//                bizOrderProcessRecord.setOrderId(order.getId());
//                bizOrderProcessRecord.setOrderProductId(order.getOrderProductId());
//                bizOrderProcessRecord.setProductId(order.getProductId());
//                List<BizOrderProcessRecord> list = bizOrderProcessRecordService.findListByOrderId(bizOrderProcessRecord);
//                if (list!=null && list.size()>0){
//                    Date createTime=null;
//                    for (BizOrderProcessRecord record : list) {
//                        createTime = record.getCreateTime();
//                        if ("0".equals(record.getCompletedVol())){
//                            if (record.getStandardHours()!=null && "0".equals(record.getWarningStatus())){
//                                Calendar calendar = Calendar.getInstance();
//                                calendar.setTime(createTime);
//                                calendar.add(Calendar.HOUR,record.getStandardHours().intValue());
//                                Date newdate = calendar.getTime();
//                                Date date=new Date();
//                                boolean b = DateUtils.compareDate(date, newdate);
//                                if (b){
//                                    record.setWarningStatus("1");
//                                    bizOrderProcessRecordService.save(record);
//
//                                    SysNotice sysNotice=new SysNotice();
//                                    sysNotice.setNoticeTitle("生产预警");
//                                    sysNotice.setNoticeType("1");
//                                    sysNotice.setNoticeContent("销售单："+record.getOrderNumber()+",地址："+record.getAddress()+"，工序："+record.getProcessName()+"已超时");
//                                    sysNotice.setNoticeContentHtml(record.getProcessName()+"已超时");
//                                    sysNotice.setStatus("0");
//                                    sysNotice.setTenantId(record.getTenantId());
//                                    sysNoticeService.save(sysNotice);
//
//                                }
//                            }
//                            break;
//                        }else {
//                            createTime=record.getCompletedTime();
//                        }
//                    }
//
//                }
//            }
//        }
//    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void ProcessWarning() {
        List<BizOrderProcessRecord> list = bizOrderProcessRecordService.findListByOrderId(new BizOrderProcessRecord());
        if (list != null && list.size() > 0) {
            Date createTime = null;
            List<String> idList=new ArrayList<>();
            for (BizOrderProcessRecord record : list) {
                if (record.getCompletedLastTime() != null) {
                    createTime = record.getCompletedLastTime();
                } else {
                    createTime = record.getCreateTime();
                }
                if (record.getStandardHours() != null && "0".equals(record.getWarningStatus())) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(createTime);
                    calendar.add(Calendar.HOUR, record.getStandardHours().intValue());
                    Date newdate = calendar.getTime();
                    Date date = new Date();
                    boolean b = DateUtils.compareDate(date, newdate);
                    if (b) {
                        idList.add(record.getOrderId());
//                        record.setWarningStatus("1");
//                        bizOrderProcessRecordService.save(record);
                        SysNotice sysNotice = new SysNotice();
                        sysNotice.setNoticeTitle("生产预警");
                        sysNotice.setNoticeType("1");
                        sysNotice.setNoticeContent("销售单：" + record.getOrderNumber() + ",地址：" + record.getAddress() + "，工序：" + record.getProcessName() + "已超时");
                        sysNotice.setNoticeContentHtml(record.getProcessName() + "已超时");
                        sysNotice.setStatus("0");
                        sysNotice.setTenantId(record.getTenantId());
                        sysNoticeService.save(sysNotice);

                    }
                }
            }
            if (idList.size()>0){
                bizOrderMapper.updateByIds(idList);
            }
        }
    }
}
